package com.qf.springcloud.filters;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.HttpStatus;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: LeeRui
 * 2021/1/17 下午 6:36
 *  使用Zuul过滤器进行权限校验
 **/
@Component
public class AuthenticationFilter extends ZuulFilter {

    @Override  //指定过滤器类型
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override  //过滤器执行顺序
    public int filterOrder() {
        return FilterConstants.SEND_FORWARD_FILTER_ORDER+100;
    }

    @Override  //过滤器开关
    public boolean shouldFilter() {
        return true;
    }

    @Override  //过滤器执行
    public Object run() throws ZuulException {
        System.out.println("过滤器执行了！！！");
        //要求客户端在请求时，必须携带参数 token=123，若没传则无权限，不让继续执行
        //获取servlet对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取request
        HttpServletRequest request = currentContext.getRequest();
        //设置判断进行请求过滤
        String token = request.getParameter("token");
        if (!"123".equalsIgnoreCase(token)){
            //请求到此终止
            currentContext.setSendZuulResponse(false);
            System.out.println("请求无权限，被拦截！");
            //过滤拦截的响应状态码
            currentContext.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
        }

        return null;
    }
}
